package com.starblink.android.basic.sensorsdata.exposure

import android.util.Log
import android.view.View
import android.view.ViewTreeObserver
import com.starblink.android.basic.sensorsdata.SkViewTracker.getTrackData
import com.starblink.android.basic.sensorsdata.exposure.config.ExposeConfig
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler

class ViewExposeDelegate(
    private val view: View,
    private val showRatio: Float = ExposeConfig.showRatio,
    private val exposeTime: Float = ExposeConfig.exposeTime
) :
    View.OnAttachStateChangeListener,
//    ViewTreeObserver.OnWindowFocusChangeListener,
    ViewTreeObserver.OnDrawListener, ViewTreeObserver.OnGlobalLayoutListener
//    ,ViewTreeObserver.OnScrollChangedListener
{

    companion object {
        private const val TAG = "ExposeViewDelegate"
    }

    private val exposeChecker by lazy {
        ExposeChecker()
    }

    init {
        view.viewTreeObserver.apply {
            //addOnWindowFocusChangeListener(this@ViewExposeDelegate)
            addOnDrawListener(this@ViewExposeDelegate)
            addOnGlobalLayoutListener(this@ViewExposeDelegate)
            //addOnScrollChangedListener(this@ViewExposeDelegate)
        }
        view.addOnAttachStateChangeListener(this)
    }

    private var lastTrackId: String? = null

    private var beenLayoutTag = false

    override fun onViewAttachedToWindow(v: View) {
        exposeChecker.updateStartTime()
//        Log.i(TAG, "onViewAttachedToWindow: ${(view.traceTagD ata)} ")
    }

    override fun onViewDetachedFromWindow(v: View) {
//        Log.i(TAG, "onViewDetachedFromWindow: ${(view.traceTagData)} ")
    }

//    override fun onWindowFocusChanged(hasFocus: Boolean) {
//        // Log.i(TAG, "onWindowFocusChanged: ${(view.javaClass.simpleName)} ")
//        // onExpose()
//    }

    private fun onExpose() {
        val tagData = view.getTrackData()
        if (tagData != null && exposeChecker.isViewExpose(view, showRatio, exposeTime)) {
            var trackEntity: SkAntEntity? = null
            if (tagData is SkAntEntity) {
                trackEntity = tagData
            }
            // 避免同id重复上报
            if (trackEntity != null && trackEntity.trackUniqueId != lastTrackId) {
                SpmTrackHandler.addSingleTrackData(trackEntity)
                lastTrackId = trackEntity.trackUniqueId
            }
            beenLayoutTag = false
        }
    }

    override fun onDraw(): Unit {
        onExpose()
    }

    override fun onGlobalLayout() {
//        Log.i(TAG, "onGlobalLayout: ${(view.traceTagData)} ")
        beenLayoutTag = true
    }

//    override fun onScrollChanged() {
////        Log.i(TAG, "onScrollChanged: ${(view.traceTagData)} ")
//        //onExpose()
//    }

}